(function() {
  "use strict";
  APP.Views.GroupListView = Backbone.View.extend({
    events : {
      'click #groupList-addGroup': 'addGroup'
    },
    initialize: function(params) {
      var callback = {
        obj: this,
        name: 'getUserGroupApplicationsSuccess'
      }
      APP.BeClient.getUserGroupApplications(callback);
    },
    getUserGroupApplicationsSuccess: function(data) {
      this.render({
        groups: data.groups,
        applications: data.applications,
      });
    },
    addGroup: function() {
      new APP.Views.DialogAddUserGroupView({
        parentView: this
      }).render();
    },
    reload: function() {
      var callback = {
        obj: this,
        name: 'getUserGroupApplicationsSuccess'
      }
      APP.BeClient.getUserGroupApplications(callback);
    },
    renderRows: function(groups) {
      var self = this;
      var tbody = this.$('#groupListTable tbody');
      tbody.html('');
      this.rowViews = [];
      _.each(groups, function(group) {
        var view = new APP.Views.GroupListRowView({
          group: group
        });
        tbody.append(view.render().el);
        self.rowViews.push(view);
      });
    },
    render: function(params) {
      this.$el.html(_.template($('#groupListTemplate').html(), {
        applications: params.applications
      }));
      this.renderRows(params.groups);
      return this;
    }
  });
}());